package com.guass.nettyprotostuff.conf;

import com.alibaba.fastjson.JSON;
import com.guass.nettyprotostuff.pojo.MsgDataInfo;
import com.guass.nettyprotostuff.rpc.common.ModelMsg;
import com.guass.nettyprotostuff.rpc.common.Session;
import com.guass.nettyprotostuff.rpc.common.SessionManager;
import com.guass.nettyprotostuff.rpc.common.TypeData;
import com.guass.nettyprotostuff.zookeeper.ZookeeperService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * @author guass
 * @date 2022年07月28日 13:32
 */
@Configuration
@Slf4j
public class MyRedisConfig {

    @Resource
    private ZookeeperService zookeeperService;

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                   MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic("guassTopic"));
        return container;
    }
    /**
     * 绑定消息监听者和接收监听的方法,必须要注入这个监听器，不然会报错
     */
    @Bean
    public MessageListenerAdapter listenerAdapter(){
        return new MessageListenerAdapter(new Receiver(),"receiveMessage");
    }

    class Receiver {
        public void receiveMessage(String message) {
            log.info("guass redis recev {}", message);
            MsgDataInfo msgDataInfo = JSON.parseObject(message, MsgDataInfo.class);
            String clientPath = msgDataInfo.getClientPath();

            if (clientPath.equals(zookeeperService.getForPath())) {

                List<Session> sessionList = SessionManager.getInstance().getSessions();

                int clientNum = msgDataInfo.getClientCount();
                int dataCount = msgDataInfo.getDataCount();
                String msg = msgDataInfo.getMsg();


                for (int i = 0; i < clientNum; i++) {
                    Session session = sessionList.get(i);
                    for (int j = 0; j < dataCount; j++) {
                        ModelMsg modelMsg = new ModelMsg();
                        modelMsg.setMessageType(TypeData.CUSTOMER);
                        modelMsg.setBody(msg);
                        modelMsg.setMsgId(UUID.randomUUID().toString());

                        session.getChannel().writeAndFlush(modelMsg);
                    }
                }
            }

        }
    }

}
